<?php
/**
 * User: 五哥派
 * Date: 2024/6/29
 * Tel(同WX): 17335592719
 */
namespace app\admin\model\store;

use app\admin\model\Base;

class Category extends Base{

    protected $name = 'store_category';


    public function getThumbAttr($value){
        return $this->prefixImageUrl($value);
    }

    public function getList($where=array(), $order = ["sort" => "desc"]){
        return self::where($where)->order($order)->paginate(100000, false);
    }

    /*public function getList($where=array(), $order = ["sort" => "desc"]){
        return self::where($where)->order($order)->paginate($this->limit, false);
    }*/
    public function getCategoyList(){
        //return self::where($where)->field('id,name,pid,sort')->select();
        $dataFirst = self::where(['pid' => 0, 'status'=>0])->field('id,name,pid,sort')->order(["sort" => "asc"])->select();
        $dataAll = self::where(['status'=>0])->field('id,name,pid,sort')->order(["sort" => "asc"])->select();
        foreach ($dataFirst as $ko => $vo) {
            $child = array();
            foreach ($dataAll as $k => $v) {
                if($v['pid'] == $vo['id']) {
                    array_push($child,$v);
                }
            }
            $vo['child'] = $child;
        }

        return $dataFirst;
    }

    /************************************* 递归相关方法 *************************************/
    public function getTree($where = array()){
        $data = self::where($where)->field('id,name,pid,sort')->select();
        return $this->_reSort($data);
    }
    private function _reSort($data, $parent_id=0, $level=0, $isClear=TRUE){
        static $ret = array();
        if($isClear)
            $ret = array();
        foreach ($data as $k => $v)
        {
            if($v['pid'] == $parent_id)
            {
                $v['level'] = $level;
                $ret[] = $v;
                $this->_reSort($data, $v['id'], $level+1, FALSE);
            }
        }
        return $ret;
    }
    public function getChildren($id, $where = array()){
        $data = self::where($where)->select();
        return $this->_children($data, $id);
    }
    private function _children($data, $parent_id=0, $isClear=TRUE)
    {
        static $ret = array();
        if($isClear)
            $ret = array();
        foreach ($data as $k => $v)
        {
            if($v['pid'] == $parent_id)
            {
                $ret[] = $v['id'];
                $this->_children($data, $v['id'], FALSE);
            }
        }
        return $ret;
    }
}